<template>
  <div class="cost-summary">
    <ProTable ref="business_table_ref" :immediate="true" :pagination="true" :search-form="formList" :columns="columns"
      :request="queryOrgBusinessPage" :onRequestSuccess="requestSuccessCallback">
      <template #extra>

        <Authc permissions="trade:merchant:business:add">
          <Button type="primary" @click="openBusinessModel()">添加</Button>
        </Authc>
      </template>
    </ProTable>


    <!-- 编辑弹窗 -->
    <Modal v-model="isShow" :visible.sync="isShow" :title="title">
      <Loading :loading="false">
        <Form ref="dataModule" :label-width="130" :model="orgBusiness" :rules="orgBusinessRuleValidate">
          <FormItem label="机构：" prop="organizationCode">
            <Select v-model="orgBusiness.organizationCode" :label-in-value="true" filterable clearable placeholder="请选择"
              @on-change="bindleOrgChange">
              <Option v-for="(item, index) in orgList" :key="item + index" :value="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
          <FormItem prop="businessCode" label="业务：">
            <Select v-model="orgBusiness.businessCodes" :label-in-value="true" filterable clearable placeholder="请选择">
              <Option v-for="(item, index) in businessList" :key="item + index" :value="item.value">{{ item.label }}
              </Option>
            </Select>
          </FormItem>
          <FormItem prop="orgPaymentChannelId" label="支付通道：">
            <Select v-model="orgBusiness.orgPaymentChannelId" :label-in-value="true" filterable clearable
              placeholder="请选择">
              <Option v-for="(item, index) in paymentChannels" :key="item + index" :value="item.value">{{ item.label }}
              </Option>
            </Select>
          </FormItem>
          <FormItem prop="clientId" label="授权应用：">
            <Select v-model="orgBusiness.clientId" :label-in-value="true" filterable clearable placeholder="请选择">
              <Option v-for="(item, index) in clients" :key="item + index" :value="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
          <FormItem prop="idPre" label="订单号前缀：">
            <Input type="input" v-model="orgBusiness.remark" placeholder="请填写订单号前缀" show-word-limit maxlength="200"
              clearable />
          </FormItem>

          <FormItem label="备注：">
            <Input type="textarea" v-model="orgBusiness.remark" placeholder="请填写" show-word-limit maxlength="200"
              clearable />
          </FormItem>
        </Form>
      </Loading>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="handleSubmitCancel('dataModule')">取消</Button>
        <Button type="primary" @click="handleSubmit('dataModule')">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import ProTable from '@/components/ProTable';
import { queryOrgBusinessPage, queryOrgBusinessById, addOrgBusiness, updateOrgBusiness, deleteOrgBusiness, allOrg } from '@/api/merchant';
import { queryBusinessList } from '@/api/merchant';

import Loading from "@/components/Loading";
import util from '@/utils/util'
import Authc from "@/components/Authc";
import { resolveComponent } from 'vue';

export default {
  name: 'OrgBusiness',
  components: {
    ProTable,
    Authc,
    Loading
  },
  data() {
    return {
      title: '机构业务管理',
      isShow: false,
      exportSection: [],
      selectExportSectionItem: {},
      orgBusiness: {
        id: null,
        organizationCode: null,
        businessCode: null,
        orgPaymentChannelId: null,
        idPre: null,
        clientId: null,
        paymentChannelCode: null,
      },
      ruleValidate: {
        businessName: [{ required: true, message: '业务名称不能为空', trigger: 'blur' }]
      },
      orgBusinessRuleValidate: {
        organizationCode: [{ required: true, message: '机构名称不能为空',type:'varchar', trigger: 'blur' }],
        businessCodes: [{ required: true, message: '请选择业务', type:'varchar', trigger: 'blur' }],
        orgPaymentChannelId: [{ required: true, message: '请选择业务', type:'varchar', trigger: 'blur' }],
        clientId: [{ required: true, message: '请选择授权应用', type:'varchar', trigger: 'blur' }],
        idPre: [{ required: true, message: '请输入订单号前缀',type:'varchar',  trigger: 'blur' }],
      },
      orgList: [],// 机构选择
      businessList: [],// 业务选择
      paymentChannels: [],// 支付通道选择
      clients: [],// 授权应用选择
      orgBusinessShow: false,
      orgBusinessTitle: '机构业务管理',
      orgBusiness: {
        organizationCode: '',// 机构编码
        businessCodes: [],// 业务编码集合
        orgPaymentChannelId: null,// 平台支付通道id
      },
      formList: [
        {
          type: 'input',
          name: 'businessName',
          label: '业务名称',
        },

      ],
      columns: [
        {
          title: '机构名称',
          key: 'organizationName',
          align: 'center',
        },
        {
          title: '机构id',
          key: 'organizationCode',
          align: 'center',
        },
        {
          title: '业务名称',
          key: 'businessName',
          align: 'center',
        },
        {
          title: '业务编码',
          key: 'businessCode',
          align: 'center',
        },
        {
          title: '机构支付通道',
          key: 'orgPaymentChannelId',
          align: 'center',
        },
        {
          title: '支付渠道编码',
          key: 'paymentChannelCode',
          align: 'center',
        },
        {
          title: '授权应用id',
          key: 'clientId',
          align: 'center',
        },
        {
          title: '操作',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.openBusinessModel(params.row)
                  }
                }
              }, '修改'),
              h('A', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.deleteItem(params.row.id)
                  }
                }
              }, '删除')
            ])
          }
        },
      ]
    };
  },
  created() {
    this.initOrgList()
  },
  methods: {
    queryOrgBusinessPage,
    async initOrgList() {
      const res = await allOrg()
      if (res.status === 200) {
        const { data } = res
        if (data) {
          console.log(data.data)
          let orgList = []
          data.data.forEach((d) => {
            orgList.push({
              label: d.organizationName,
              value: d.organizationCode
            })
          })
          this.orgList = orgList
          console.log("this.orgList:", orgList)
        }
      }
      console.log('initOrgList:', res)
    },
    async selectExportSection(item) {
      this.selectExportSectionItem = item
    },
    //查询成功回调
    async requestSuccessCallback(res) {
      if (res && res.data.pagination) {
        const total = res.data.pagination.total || 0
        if (total) {
          const sections = Math.ceil(total / 5000)
          let newExportSection = []
          for (let i = 1; i <= sections; i++) {
            newExportSection.push({
              id: i,
              start: (i - 1) * 5000 === 0 ? 1 : (i - 1) * 5000,
              end: i * 5000
            })
          }
          console.log(this.exportSection)
          this.exportSection = newExportSection
        } else {
          this.exportSection = []
        }
      } else {
        this.exportSection = []
      }
    },

    async openBusinessModel(params) {
      if (params && params.id) {
        const { data: { ret, data } } = await queryOrgBusinessById(params.id)
        this.orgBusiness = data
        this.addtype = "update"
      } else {
        this.addtype = "add"
      }
      this.isShow = true

    },

    handleSubmitCancel(formName) {
      this.isShow = false
      this.$refs[formName].resetFields()
    },
    async handleSubmit(name) {
      let that = this
      that.$refs[name].validate(async valid => {
        if (valid) {
          if (that.addtype === 'add') {
            await addOrgBusiness(this.orgBusiness)

          } else {
            await updateOrgBusiness(this.orgBusiness)
          }
          that.$refs.business_table_ref.onSearch();
          that.isShow = false;

        } else {
          console.log('error submit!!')
          // return false
        }
      })
    },
    // 重置
    resetForm() {
      if (this.$refs['dataModule'].fields) {
        this.$refs['dataModule'].fields.forEach(function (e) {
          if (e.prop == 'businessName') e.resetField();
        })
      }
    },

    async deleteItem(id) {
      const that = this
      this.$Modal.confirm({
        title: '提示',
        content: '是否确认删除该业务类型？',
        onOk: async () => {
          await deleteOrgBusiness(id)
          that.$refs.business_table_ref.onSearch();
        },
        onCancel: () => {
        }
      });

    },
    async bindleOrgChange(item) {
      if (item) {
        const res= await queryBusinessList()
        const {data}=res
        console.log(data)
        // 查询业务list
        if (data && data.data) {
            let businessList = []
            data.data.forEach((d) => {
              businessList.push({
                label: d.businessName,
                value: d.businessCode
              })
            })
            this.businessList = businessList
          }
      } else {
        this.businessList = []
      }

    }
  }
};
</script>

<style>
.selectSectionItem {
  color: #2b85e4;
}
</style>
